from urllib import request,parse
import json
import hashlib
import time
import random

def translate(key):
    salt = str(int(time.time() * 1000) + random.randint(0, 10))
    sign = "fanyideskweb" + key + salt + "ebSeFb%=XZ%T[KZ)c(sy!"
    m = hashlib.md5()
    m.update(sign.encode('utf-8'))

    data = {
            'i': key,
            'from': 'en',
            'to': 'zh-CHS',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': salt,
            'sign': m.hexdigest(),
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTIME',
            'typoResult': 'false',
    }
    data = parse.urlencode(data)

    headers = {
            'Cookie': 'OUTFOX_SEARCH_USER_ID=2084716981@114.111.166.79;',
            'Referer': 'http://fanyi.youdao.com/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; rv:51.0) Gecko/20100101 Firefox/51.0',
    }
    url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"

    req = request.Request(url=url,data=bytes(data,encoding='utf-8'),headers=headers)
    res = request.urlopen(req)

    html = res.read().decode('utf-8')
    result = json.loads(html)
    print("翻译结果：")
    print()

    print(result['translateResult'][0][0]['tgt'])

    for i in range(len(result['smartResult']['entries'])):
            s = result['smartResult']['entries'][i]
            s = s.replace("\n", "")
            print(s)

    print()

if __name__ == '__main__':
    while True:
        key=input("请输入要翻译的单词：")
        if key=='q':
            break
        else:
            translate(key)



